package net.privatenav.exia;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Choreographer.FrameCallback;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class List_promo extends ListFragment {
		
	private ListView lv;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		 View V = inflater.inflate(R.layout.activity_list_promo, container, false);
		
		
     try {
    	 CAsyncTask task = new CAsyncTask ();
         task.execute();
     } catch (Exception e) {
	        Log.e("log_tag_lol", "Error  ");
	}
    
		return V;
    }
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		 display();
	}
	
	private void display()
	{
		final
		Context context = getActivity().getApplicationContext();
		lv = (ListView) getView().findViewById(android.R.id.list);
	     lv.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
				
							switch((int) lv.getItemIdAtPosition((int) arg3))
							{
							case 0 :
								Intent myIntent = new Intent(List_promo.this.getActivity().getApplicationContext(), Liste_eleves.class);
								myIntent.putExtra("promo", "A1");
								List_promo.this.startActivity(myIntent);
								Log.e("log_button", "Error A1 ");
								break;
							case 1 :
								Intent myIntent1 = new Intent(context, Liste_eleves.class);
								myIntent1.putExtra("promo", "A2");
								List_promo.this.startActivity(myIntent1);
								break;
							case 2 :
								Intent myIntent2 = new Intent(context, Liste_eleves.class);
								myIntent2.putExtra("promo", "A3");
								List_promo.this.startActivity(myIntent2);
								break;
							case 3 :
								Intent myIntent3 = new Intent(context, Liste_eleves.class);
								myIntent3.putExtra("promo", "A4");
								List_promo.this.startActivity(myIntent3);
								break;
							case 4 :
								Intent myIntent4 = new Intent(context, Liste_eleves.class);
								myIntent4.putExtra("promo", "A5");
								List_promo.this.startActivity(myIntent4);
								break;
								
							}
				}
			});
	}
	
	private class CAsyncTask extends AsyncTask<Void, Void, ArrayList<HashMap<String, Object>>> {
    	ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
    	Context context = getActivity().getApplicationContext();
		@Override
        protected ArrayList<HashMap<String, Object>> doInBackground (Void... args) {
        	String result = "";
    		//the year data to send
    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    		InputStream is = null;
    		
    		//http post
    		try{
    		        HttpClient httpclient = new DefaultHttpClient();
    		        HttpPost httppost = new HttpPost("http://privatenav.net/exia/requetes_liste_promo.php");
    		        HttpResponse response = httpclient.execute(httppost);
    		        HttpEntity entity = response.getEntity();
    		         is = entity.getContent();
    		}catch(Exception e){
    		        Log.e("log_tag", "Error in http connection "+e.toString());
    		}
    		//convert response to string
    		try{
    		        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    		        StringBuilder sb = new StringBuilder();
    		        String line = null;
    		        while ((line = reader.readLine()) != null) {
    		                sb.append(line + "\n");
    		        }
    		        is.close();
    		 
    		        result=sb.toString();
    		}catch(Exception e){
    		        Log.e("log_tag", "Error converting result "+e.toString());
    		}
    		 
    		//parse json data
    		try{
        		JSONArray jArray = new JSONArray(result);
            	JSONObject json_data=null;
            	for(int i=0;i<jArray.length();i++)
            	{
            		HashMap<String, Object> map;
                    map = new HashMap<String, Object>();
                   json_data = jArray.getJSONObject(i);
                   map.put("nom","> Promotion"+json_data.getString("nom"));
                   listItem.add(map);
               }
            	return listItem;
            }
            catch(JSONException e1){
            	//Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
            	Log.e("log_tag e1", "Error "+e1.toString());
            } catch (ParseException e1) {
            	//Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
            	Log.e("log_tag e1", "Error "+e1.toString());
      	}
        	return null;
            } // doInBackground ();
            
            @Override
            protected void onPostExecute (ArrayList<HashMap<String, Object>> _list) {
            	if(_list == null)
            	{
            		Log.e("log_tag_null", "Error ");
            	}
            	else
            	{
                SimpleAdapter adapter = new SimpleAdapter(context, _list, R.layout.promos_listing, new String[] {"nom"}, new int[] {R.id.nom_promo});
            	adapter.setViewBinder(new MyViewBinder());
            	lv.setAdapter(adapter);
            	}
            } // onPostExecute ();

    	
            
        } // CAsyncTask ();
}
